
package com.shop.cloud.mall.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.mall.admin.service.GoodsSpuService;
import com.shop.cloud.mall.admin.service.SupplierGoodsSpuService;
import com.shop.cloud.mall.common.entity.GoodsSpu;
import com.shop.cloud.mall.common.entity.Supplier;
import com.shop.cloud.mall.admin.mapper.SupplierMapper;
import com.shop.cloud.mall.admin.service.SupplierService;
import com.shop.cloud.mall.common.entity.SupplierGoodsSpu;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 供应商
 *
 * @author
 * @date 2023-04-20 10:25:10
 */
@Service
@AllArgsConstructor
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {

    private final GoodsSpuService goodsSpuService;
    private final SupplierGoodsSpuService supplierGoodsSpuService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(Supplier entity) {
        if(CommonConstants.NO.equals(entity.getEnable())){//关闭供应商则下架相应店铺和供应商的商品
            //下架供应商商品
            SupplierGoodsSpu supplierGoodsSpu = new SupplierGoodsSpu();
            supplierGoodsSpu.setShelf(CommonConstants.NO);
            supplierGoodsSpuService.update(supplierGoodsSpu,Wrappers.<SupplierGoodsSpu>lambdaQuery()
                    .eq(SupplierGoodsSpu::getSupplierId, entity.getId()));

            //查询出该供应商商品关联的所有上架的店铺商品ID
            List<String> listIds = goodsSpuService.list(Wrappers.<GoodsSpu>query().lambda()
                    .eq(GoodsSpu::getShelf, CommonConstants.YES)
                    .eq(GoodsSpu::getSupplierId, entity.getId())).stream().map(GoodsSpu::getId).collect(Collectors.toList());
            //下架店铺商品
            if(listIds.size() > 0){
                goodsSpuService.shelf(CommonConstants.NO, StrUtil.join(",", listIds));
            }
        }
        return super.updateById(entity);
    }
}
